package com.fanshilz.flower2025.apps.wechatminiapp.project.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.fanshilz.flower2025.apps.admin.aliyun.req.AttachmentUploadReq;
import com.fanshilz.flower2025.apps.wechatminiapp.project.req.*;
import com.fanshilz.flower2025.apps.wechatminiapp.project.resp.*;
import com.fanshilz.flower2025.apps.wechatminiapp.satoken.StpWechatUtil;
import com.fanshilz.flower2025.apps.wechatminiapp.satoken.WechatCurrentUser;
import com.fanshilz.flower2025.business.flower.addressCode.service.IAddressCodeService;
import com.fanshilz.flower2025.business.flower.attachment.entity.Attachment;
import com.fanshilz.flower2025.business.flower.attachment.service.IAttachmentService;
import com.fanshilz.flower2025.business.flower.project.entity.CreateUserTypeEnum;
import com.fanshilz.flower2025.business.flower.project.entity.Project;
import com.fanshilz.flower2025.business.flower.project.entity.ProjectStatusEnum;
import com.fanshilz.flower2025.business.flower.project.service.IProjectService;
import com.fanshilz.flower2025.business.flower.projectBid.entity.ProjectBid;
import com.fanshilz.flower2025.business.flower.projectBid.service.IProjectBidService;
import com.fanshilz.flower2025.business.flower.projectBrowse.entity.ProjectBrowse;
import com.fanshilz.flower2025.business.flower.projectBrowse.service.IProjectBrowseService;
import com.fanshilz.flower2025.business.flower.projectCollect.entity.CollectStatusEnum;
import com.fanshilz.flower2025.business.flower.projectCollect.entity.ProjectCollect;
import com.fanshilz.flower2025.business.flower.projectCollect.service.IProjectCollectService;
import com.fanshilz.flower2025.business.flower.projectLink.entity.ProjectLink;
import com.fanshilz.flower2025.business.flower.projectLink.entity.ProjectLinkStatusEnum;
import com.fanshilz.flower2025.business.flower.projectLink.service.IProjectLinkService;
import com.fanshilz.flower2025.business.flower.projectMore.entity.ProjectMore;
import com.fanshilz.flower2025.business.flower.projectMore.service.IProjectMoreService;
import com.fanshilz.flower2025.business.flower.searchRecord.entity.SearchRecord;
import com.fanshilz.flower2025.business.flower.searchRecord.service.ISearchRecordService;
import com.fanshilz.flower2025.business.flower.wechatUser.entity.WechatUser;
import com.fanshilz.flower2025.business.flower.wechatUser.service.IWechatUserService;
import com.fanshilz.flower2025.framework.aliyun.sms.AliyunSmsUtil;
import com.fanshilz.flower2025.framework.aliyun.sts.AliyunSts;
import com.fanshilz.flower2025.framework.aliyun.sts.AliyunStsUtil;
import com.fanshilz.flower2025.framework.exception.CodeException;
import com.fanshilz.flower2025.framework.resp.Resp;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.row.Row;
import io.github.linpeilie.Converter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

import static com.fanshilz.flower2025.business.flower.addressCode.entity.table.AddressCodeTableDef.ADDRESS_CODE;
import static com.fanshilz.flower2025.business.flower.project.entity.table.ProjectTableDef.PROJECT;
import static com.fanshilz.flower2025.business.flower.projectBid.entity.table.ProjectBidTableDef.PROJECT_BID;
import static com.fanshilz.flower2025.business.flower.projectBrowse.entity.table.ProjectBrowseTableDef.PROJECT_BROWSE;
import static com.fanshilz.flower2025.business.flower.projectCollect.entity.table.ProjectCollectTableDef.PROJECT_COLLECT;
import static com.fanshilz.flower2025.business.flower.projectLink.entity.table.ProjectLinkTableDef.PROJECT_LINK;
import static com.fanshilz.flower2025.business.flower.searchRecord.entity.table.SearchRecordTableDef.SEARCH_RECORD;
import static com.fanshilz.flower2025.business.flower.wechatUser.entity.table.WechatUserTableDef.WECHAT_USER;
import static com.mybatisflex.core.query.QueryMethods.max;

@Tag(name = "线索")
@RestController
@RequestMapping("/wechat/project")
public class WechatProjectController {

    @Resource
    private Converter converter;
    @Resource
    private IProjectService projectService;
    @Resource
    private IAttachmentService attachmentService;
    @Resource
    private IAddressCodeService addressCodeService;
    @Resource
    private IProjectCollectService projectCollectService;
    @Resource
    private IProjectBrowseService projectBrowseService;
    @Resource
    private IProjectBidService projectBidService;
    @Resource
    private IProjectMoreService projectMoreService;
    @Resource
    private ISearchRecordService searchRecordService;
    @Resource
    private IProjectLinkService projectLinkService;
    @Resource
    private IWechatUserService wechatUserService;

    @Operation(summary = "请求联系信息")
    @PostMapping("/requestLinkInformation")
    public Resp<RequestLinkInformationResp> requestLinkInformation(@RequestBody @Valid RequestLinkInformationReq req) {
        WechatUser user = wechatUserService.getOne(QueryWrapper.create()
                .select(WECHAT_USER.USER_MOBILE)
                .where(WECHAT_USER.USER_ID.eq(req.getLinkToUserId())));

//        Project p = projectService.getOne(QueryWrapper.create()
//                .select(PROJECT.PROJECT_USER_NAME)
//                .where(PROJECT.PROJECT_ID.eq(req.getLinkProjectId())));

        return Resp.success(new RequestLinkInformationResp(user.getUserMobile()));
    }

    @Operation(summary = "请求联系操作")
    @PostMapping("/requestLinkHandle")
    public Resp<Void> requestLinkHandle(@RequestBody @Valid RequestLinkHandleReq req) {
        projectLinkService.updateById(ProjectLink.builder()
                .linkId(req.getLinkId())
                .linkStatusLabel(req.getLinkStatusLabel())
                .linkStatusValue(req.getLinkStatusValue())
                .build());
        ProjectLink pl = projectLinkService.getOne(QueryWrapper.create()
                .select(PROJECT_LINK.CREATE_USER_ID)
                .where(PROJECT_LINK.LINK_ID.eq(req.getLinkId())));

        WechatUser one = wechatUserService.getOne(QueryWrapper.create()
                .select(WECHAT_USER.USER_MOBILE)
                .where(PROJECT_LINK.LINK_ID.eq(pl.getLinkId())));

        if (ObjUtil.isNotNull(one) && StrUtil.isNotBlank(one.getUserMobile())) {
            if (req.getLinkStatusValue() == 1) {
                // 同意
                AliyunSmsUtil.sendTemplateCode("SMS_479085661", one.getUserMobile());
            } else if (req.getLinkStatusValue() == 2) {
                // 拒绝
                AliyunSmsUtil.sendTemplateCode("SMS_479105608", one.getUserMobile());
            }
        }

        return Resp.success();
    }

    @Operation(summary = "请求联系详情")
    @PostMapping("/requestLinkDetail")
    public Resp<RequestLinkDetailResp> requestLinkDetail(@RequestBody @Valid RequestLinkDetailReq req) {
//        ProjectLink pl = projectLinkService.getById(req.getLinkId());
        RequestLinkDetailResp resp = projectLinkService.getOneAs(QueryWrapper.create()
                .where(PROJECT_LINK.LINK_ID.eq(req.getLinkId())), RequestLinkDetailResp.class);
        return Resp.success(resp);
    }

    @Operation(summary = "请求联系列表")
    @PostMapping("/requestLinkList")
    public Resp<List<RequestLinkListResp>> requestLinkList(@RequestBody @Valid RequestLinkListReq req) {
        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        QueryWrapper qw = QueryWrapper.create()
                .where(PROJECT_LINK.LINK_TO_USER_ID.eq(currentUser.getUserId()))
                .orderBy(PROJECT_LINK.LINK_ID.desc());
        Page<RequestLinkListResp> resp = projectLinkService.pageAs(Page.of(req.getCurrent(), req.getSize()), qw, RequestLinkListResp.class);
        return Resp.success(resp.getRecords());
    }

    @Operation(summary = "请求联系")
    @PostMapping("/requestLink")
    public Resp<Void> requestLink(@RequestBody @Valid RequsetLinkReq req) {
        ProjectLink pl = converter.convert(req, ProjectLink.class);
        pl.setLinkStatusLabel(ProjectLinkStatusEnum.WAIT_CHECK.getLable());
        pl.setLinkStatusValue(ProjectLinkStatusEnum.WAIT_CHECK.getValue());
        if (req.getLinkFromMobile().contains("****")) {
            WechatCurrentUser currentUser = StpWechatUtil.currentUser();
            pl.setLinkFromMobile(currentUser.getUserMobile());
        }
        Project p = projectService.getOne(QueryWrapper.create()
                .select(PROJECT.CREATE_USER_TYPE, PROJECT.CREATE_USER_ID, PROJECT.PROJECT_USER_MOBILE)
                .where(PROJECT.PROJECT_ID.eq(req.getLinkProjectId())));
        if (CreateUserTypeEnum.WECHAT_USER.getValue().equals(p.getCreateUserType())) {
            // 微信用户创建
            pl.setLinkToUserId(p.getCreateUserId());
        } else {
            return Resp.error("请联系管理员，代码1101");
        }
        projectLinkService.save(pl);
        if (StrUtil.isNotBlank(p.getProjectUserMobile())) {
            AliyunSmsUtil.sendTemplateCode("SMS_479070638", p.getProjectUserMobile());
        }
        return Resp.success();
    }

    @Operation(summary = "请求联系线索详情")
    @PostMapping("/requestLinkProjectDetail")
    public Resp<RequestLinkProjectDetailResp> requestLinkProjectDetail(@RequestBody @Valid RequestLinkProjectDetailReq req) {
        RequestLinkProjectDetailResp resp = projectService.getMapper()
                .selectOneWithRelationsByQueryAs(QueryWrapper.create()
                        .where(PROJECT.PROJECT_ID.eq(req.getProjectId())), RequestLinkProjectDetailResp.class);
        return Resp.success(resp);
    }

    @Operation(summary = "搜索历史")
    @PostMapping("/searchRecord")
    public Resp<List<SearchRecordResp>> searchRecord() {
        List<SearchRecordResp> resp = searchRecordService.listAs(QueryWrapper.create()
                .where(SEARCH_RECORD.CREATE_USER_ID.eq(StpWechatUtil.currentUser().getUserId()))
                .limit(10)
                .orderBy(SEARCH_RECORD.SR_ID.desc()), SearchRecordResp.class);
        return Resp.success(resp);
    }

    @Operation(summary = "线索编辑提交")
    @PostMapping("/editSubmit")
    public Resp<Void> editSubmit(@RequestBody @Valid WechatProjectUpdateReq req) {
        Project p = converter.convert(req, Project.class);
        boolean b = projectService.updateById(p);
        Assert.isTrue(b, CodeException::new);
        return Resp.success();
    }

    @Operation(summary = "线索编辑详情")
    @PostMapping("/editDetail")
    public Resp<WechatProjectEditDetailDesp> editDetail(@RequestBody @Valid WechatProjectEditDetailReq req) {
        QueryWrapper qw = QueryWrapper.create()
                .where(PROJECT.PROJECT_ID.eq(req.getProjectId()));
        WechatProjectEditDetailDesp resp = projectService.getMapper().selectOneWithRelationsByQueryAs(qw, WechatProjectEditDetailDesp.class);
        return Resp.success(resp);
    }

    @Operation(summary = "线索撤回")
    @PostMapping("/revocation")
    public Resp<Void> revocation(@RequestBody @Valid WechatProjectRevocationController req) {
        boolean b = projectService.updateById(Project.builder()
                .projectId(req.getProjectId())
                .projectStatusValue(ProjectStatusEnum.DELIST.getValue())
                .projectStatusLabel(ProjectStatusEnum.DELIST.getLable())
                .build());
        Assert.isTrue(b, CodeException::new);
        return Resp.success();
    }

    @Operation(summary = "更多信息")
    @PostMapping("/more")
    public Resp<Void> more(@RequestBody @Valid ProjectMoreReq req) {
        ProjectMore pm = converter.convert(req, ProjectMore.class);
        boolean save = projectMoreService.save(pm);
        Assert.isTrue(save, CodeException::new);
        return Resp.success();
    }

    @Operation(summary = "出价")
    @PostMapping("/bid")
    public Resp<Void> bid(@RequestBody @Valid WechatProjectBidReq req) {
        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        long count = projectBidService.count(PROJECT_BID.CREATE_USER_ID.eq(currentUser.getUserId()).and(PROJECT_BID.PROJECT_ID.eq(req.getProjectId())));
        Assert.isTrue(count <= 0, () -> new CodeException("已叫价"));

        boolean save = projectBidService.save(ProjectBid.builder().projectId(req.getProjectId()).bidPriceMoney(req.getBidPriceMoney()).build());
        Assert.isTrue(save, CodeException::new);
        return Resp.success();
    }

    @Operation(summary = "我的收藏")
    @PostMapping("/iCollects")
    public Resp<List<ProjectCollectsResp>> iCollects(@RequestBody @Valid IBrowsesReq req) {
        QueryWrapper qw = QueryWrapper.create();
        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        qw.select(PROJECT.ALL_COLUMNS, PROJECT_COLLECT.COLLECT_ID);
        qw.innerJoin(PROJECT_COLLECT).on(PROJECT.PROJECT_ID.eq(PROJECT_COLLECT.PROJECT_ID))
                .where(PROJECT_COLLECT.COLLECT_STATUS_VALUE.eq(CollectStatusEnum.TRUE))
                .where(PROJECT_COLLECT.CREATE_USER_ID.eq(currentUser.getUserId()));

        Page<ProjectCollectsResp> page = projectService.getMapper()
                .paginateWithRelationsAs(Page.of(req.getCurrent(), req.getSize()), qw, ProjectCollectsResp.class);
        return Resp.success(page.getRecords());
    }

    @Operation(summary = "浏览记录")
    @PostMapping("/iBrowses")
    public Resp<List<ProjectBrowsesResp>> iBrowses(@RequestBody @Valid IBrowsesReq req) {
        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        QueryWrapper qw = QueryWrapper.create();
        qw.select(PROJECT_BROWSE.PROJECT_ID, max(PROJECT_BROWSE.CREATE_TIME))
                .where(PROJECT_BROWSE.CREATE_USER_ID.eq(currentUser.getUserId()))
                .groupBy(PROJECT_BROWSE.PROJECT_ID)
                .orderBy(max(PROJECT_BROWSE.CREATE_TIME).desc());

        Page<Row> page = projectBrowseService.pageAs(Page.of(req.getCurrent(), req.getSize()), qw, Row.class);

        if (CollUtil.isEmpty(page.getRecords())) {
            return Resp.success();
        }

        List<Long> projectIds = page.getRecords().stream().map(r -> r.getLong("project_id")).toList();

        List<ProjectBrowsesResp> resps = projectService.getMapper()
                .selectListWithRelationsByQueryAs(QueryWrapper.create().where(PROJECT.PROJECT_ID.in(projectIds)), ProjectBrowsesResp.class);

        return Resp.success(resps);
    }

    @Operation(summary = "我发布的/我出售的")
    @PostMapping("/iPublish")
    public Resp<List<IPublishProjectResp>> iPublish(@RequestBody @Valid IPublishReq req) {
        QueryWrapper qw = QueryWrapper.create();
        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        qw.select(PROJECT.PROJECT_ID,
                PROJECT.PROJECT_UUID,
                PROJECT.PROJECT_NAME,
                PROJECT.PROJECT_SELLING_PRICE_MONEY,
                PROJECT.PROJECT_STATUS_LABEL,
                PROJECT.PROJECT_STATUS_VALUE,
                PROJECT.CREATE_TIME);
        qw.where(PROJECT.CREATE_USER_TYPE.eq(CreateUserTypeEnum.WECHAT_USER))
                .where(PROJECT.CREATE_USER_ID.eq(currentUser.getUserId()));
        if (req.getType() == 0) {
            qw.where(PROJECT.PROJECT_STATUS_VALUE.in(ProjectStatusEnum.WAIT_CHECK, ProjectStatusEnum.REJECT, ProjectStatusEnum.PASS, ProjectStatusEnum.PUTAWAY));
        } else if (req.getType() == 1) {
            qw.where(PROJECT.PROJECT_STATUS_VALUE.in(ProjectStatusEnum.WAIT_LISTED, ProjectStatusEnum.COMPLETE_TRANSACTION, ProjectStatusEnum.IN_TRADING, ProjectStatusEnum.DELIST));
        }
        Page<IPublishProjectResp> page = projectService.pageAs(Page.of(req.getCurrent(), req.getSize()), qw, IPublishProjectResp.class);
        return Resp.success(page.getRecords());
    }

    @Operation(summary = "收藏")
    @PostMapping("/projectCollect")
    public Resp<ProjectCollectIdResp> projectCollect(@RequestBody @Valid WechatProjectCollectReq req) {
        ProjectCollect pc = converter.convert(req, ProjectCollect.class);

        pc.setCollectStatusLabel(Arrays.stream(CollectStatusEnum.values())
                .filter(collectStatusEnum -> collectStatusEnum.getValue().equals(pc.getCollectStatusValue())).findFirst().get().getLable());

        projectCollectService.saveOrUpdate(pc);

        return Resp.success(new ProjectCollectIdResp(pc.getCollectId()));
    }

    @Operation(summary = "行政编码检索")
    @PostMapping("/addressCode/search")
    public Resp<List<AddressCodeResp>> addressCodeSearch(@RequestBody @Valid WechatAddressCodeSearchReq req) {
        if (StrUtil.isAllBlank(req.getCityCode(), req.getCityName(), req.getProvinceCode())) {
            return Resp.success();
        }
        QueryWrapper qw = QueryWrapper.create();
        if (StrUtil.isNotBlank(req.getCityName())) {
            if ("hotCitys".equals(req.getCityName())) {
                qw.where(ADDRESS_CODE.TYPE.eq(1));
                qw.where(ADDRESS_CODE.CITY_CODE.in("4403", "1301", "5101", "2301", "3702", "1101", "3101", "4401", "3201", "3205"));
            } else if ("province".equals(req.getCityName())) {
                qw.where(ADDRESS_CODE.TYPE.eq(0));
            } else {
                qw.where(ADDRESS_CODE.TYPE.eq(1));
                qw.where(ADDRESS_CODE.CITY_NAME.like(req.getCityName()));
            }
        }
        if (StrUtil.isNotBlank(req.getProvinceCode())) {
            qw.where(ADDRESS_CODE.TYPE.eq(1));
            qw.where(ADDRESS_CODE.PROVINCE_CODE.eq(req.getProvinceCode()));
        }
        if (StrUtil.isNotBlank(req.getCityCode())) {
            qw.where(ADDRESS_CODE.TYPE.eq(2));
            qw.where(ADDRESS_CODE.CITY_CODE.eq(req.getCityCode()));
        }
        List<AddressCodeResp> addressCodeResps = addressCodeService.listAs(qw, AddressCodeResp.class);
        return Resp.success(addressCodeResps);
    }

    @Operation(summary = "线索详情")
    @PostMapping("/projectDetail")
    public Resp<WechatProjectDetailDesp> projectDetail(@RequestBody @Valid WechatProjectDetailReq req) {

        WechatCurrentUser currentUser = StpWechatUtil.currentUser();
        RelationManager.addExtraConditionParam("createUserId", currentUser.getUserId());

        WechatProjectDetailDesp one = projectService.getMapper()
                .selectOneWithRelationsByQueryAs(QueryWrapper.create()
                        .where(PROJECT.PROJECT_ID.eq(req.getProjectId())), WechatProjectDetailDesp.class);

        // 记录浏览记录
        projectBrowseService.save(ProjectBrowse.builder().projectId(req.getProjectId()).build());

        return Resp.success(one);
    }

    @Operation(summary = "线索检索 首页/筛选")
    @PostMapping("/search")
    public Resp<List<ProjectSearchItemResp>> search(@RequestBody @Valid WechatProjectSearchReq req) {
        QueryWrapper qw = QueryWrapper.create()
                .select(PROJECT.PROJECT_ID,
                        PROJECT.PROJECT_UUID,
                        PROJECT.PROJECT_SHORT_NAME,
                        PROJECT.PROJECT_INCOME_YEAR_MONEY,
                        PROJECT.PROJECT_PROFIT_YEAR_MONEY,
                        PROJECT.PROJECT_SELLING_PRICE_MONEY,
                        PROJECT.PROJECT_FOUNDING_TIME_YEAR,
                        PROJECT.PROJECT_PROVINCE_NAME,
                        PROJECT.PROJECT_PROVINCE_CODE,
                        PROJECT.PROJECT_CITY_NAME,
                        PROJECT.PROJECT_CITY_CODE,
                        PROJECT.PROJECT_AREA_NAME,
                        PROJECT.PROJECT_AREA_CODE)
                .where(PROJECT.PROJECT_STATUS_VALUE.eq(ProjectStatusEnum.PUTAWAY.getValue()))
                .where(PROJECT.PROJECT_SHORT_NAME.like(req.getProjectShortName())
                        .when(StrUtil.isNotBlank(req.getProjectShortName())))
                .where(PROJECT.PROJECT_INDUSTRY_VALUE.in(req.getProjectIndustrys()))
                .where(PROJECT.PROJECT_TYPE_VALUE.in(req.getProjectTypes()))
                .where(PROJECT.PROJECT_PROVINCE_CODE.eq(req.getProjectProvinceCode())
                        .when(StrUtil.isNotBlank(req.getProjectProvinceCode())))
                .where(PROJECT.PROJECT_CITY_CODE.eq(req.getProjectCityCode())
                        .when(StrUtil.isNotBlank(req.getProjectCityCode())))
                .where(PROJECT.PROJECT_AREA_CODE.eq(req.getProjectAreaCode())
                        .when(StrUtil.isNotBlank(req.getProjectAreaCode())))
                .where(PROJECT.PROJECT_INCOME_YEAR_MONEY.eq(req.getOperatingIncomeValue()))
                .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(req.getProfitMin()))
                .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(req.getProfitMax()));

        if (ObjUtil.isNotNull(req.getEstablishmentTimeType())) {
            if (req.getEstablishmentTimeType() == 0) {
                qw.where(PROJECT.PROJECT_FOUNDING_TIME_YEAR.le(2));
            } else if (req.getEstablishmentTimeType() == 1) {
                qw.where(PROJECT.PROJECT_FOUNDING_TIME_YEAR.ge(2)
                        .and(PROJECT.PROJECT_FOUNDING_TIME_YEAR.le(5)));
            } else if (req.getEstablishmentTimeType() == 2) {
                qw.where(PROJECT.PROJECT_FOUNDING_TIME_YEAR.ge(5)
                        .and(PROJECT.PROJECT_FOUNDING_TIME_YEAR.le(10)));
            } else if (req.getEstablishmentTimeType() == 3) {
                qw.where(PROJECT.PROJECT_FOUNDING_TIME_YEAR.ge(10));
            }
        }

        if (ObjUtil.isNotNull(req.getEmployeesNumberType())) {
            if (req.getEmployeesNumberType() == 0) {
                qw.where(PROJECT.PROJECT_EMPLOYEES_NUMBER.lt(50));
            } else if (req.getEmployeesNumberType() == 1) {
                qw.where(PROJECT.PROJECT_EMPLOYEES_NUMBER.ge(50)
                        .and(PROJECT.PROJECT_EMPLOYEES_NUMBER.le(99)));
            } else if (req.getEmployeesNumberType() == 2) {
                qw.where(PROJECT.PROJECT_EMPLOYEES_NUMBER.ge(100)
                        .and(PROJECT.PROJECT_EMPLOYEES_NUMBER.le(999)));
            } else if (req.getEmployeesNumberType() == 3) {
                qw.where(PROJECT.PROJECT_EMPLOYEES_NUMBER.ge(1000));
            }
        }

        if (ObjUtil.isNotNull(req.getOperatingIncomeType())) {
            if (req.getOperatingIncomeType() == 0) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.le(199));
            } else if (req.getOperatingIncomeType() == 1) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.ge(200)
                        .and(PROJECT.PROJECT_INCOME_YEAR_MONEY.le(499)));
            } else if (req.getOperatingIncomeType() == 2) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.ge(500)
                        .and(PROJECT.PROJECT_INCOME_YEAR_MONEY.le(2999)));
            } else if (req.getOperatingIncomeType() == 3) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.ge(3000)
                        .and(PROJECT.PROJECT_INCOME_YEAR_MONEY.le(4999)));
            } else if (req.getOperatingIncomeType() == 4) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.ge(5000)
                        .and(PROJECT.PROJECT_INCOME_YEAR_MONEY.le(9999)));
            } else if (req.getOperatingIncomeType() == 5) {
                qw.where(PROJECT.PROJECT_INCOME_YEAR_MONEY.ge(10000));
            }
        }

        if (ObjUtil.isNotNull(req.getProfitType())) {
            if (req.getProfitType() == 0) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(199));
            } else if (req.getProfitType() == 1) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(200))
                        .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(499));
            } else if (req.getProfitType() == 2) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(500))
                        .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(2999));
            } else if (req.getProfitType() == 3) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(3000))
                        .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(4999));
            } else if (req.getProfitType() == 4) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(5000))
                        .where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.le(9999));
            } else if (req.getProfitType() == 5) {
                qw.where(PROJECT.PROJECT_PROFIT_YEAR_MONEY.ge(10000));
            }
        }

        if (req.getSortType() == 0) {
            qw.orderBy(PROJECT.PROJECT_SORT.desc(), PROJECT.PROJECT_PUBLISH_TIME.desc());
        } else if (req.getSortType() == 1) {
            qw.orderBy(PROJECT.PROJECT_PUBLISH_TIME.desc());
        } else if (req.getSortType() == 2) {
            qw.orderBy(PROJECT.PROJECT_SELLING_PRICE_MONEY.desc());
        } else if (req.getSortType() == 3) {
            qw.orderBy(PROJECT.PROJECT_SELLING_PRICE_MONEY.asc());
        }

        Page<ProjectSearchItemResp> resp = projectService.getMapper().paginateWithRelationsAs(Page.of(req.getCurrent(), req.getSize()), qw, ProjectSearchItemResp.class);

        if (StrUtil.isNotBlank(req.getProjectShortName())) {
            searchRecordService.save(SearchRecord.builder().srValue(req.getProjectShortName()).build());
        }

        return Resp.success(resp.getRecords());
    }

    @Operation(summary = "附件信息上传")
    @PostMapping("/attachmentUpload")
    public Resp<Void> attachmentUpload(@RequestBody @Valid @NotEmpty List<AttachmentUploadReq> req) {
        for (AttachmentUploadReq attachmentUploadReq : req) {
            if (ObjUtil.isNull(attachmentUploadReq.getObjId()) && StrUtil.isBlank(attachmentUploadReq.getObjIdStr())) {
                return Resp.error("objId或objIdStr必填其一");
            }
        }

        List<Attachment> attachments = converter.convert(req, Attachment.class);
        boolean b = attachmentService.saveBatch(attachments);
        Assert.isTrue(b, CodeException::new);

        return Resp.success();
    }

    @Operation(summary = "线索创建")
    @PostMapping("/create")
    public Resp<ProjectCreateResp> create(@RequestBody @Valid WechatProjectCreateReq req) {
        Project p = converter.convert(req, Project.class);
        p.setProjectUuid("1" + RandomUtil.randomNumbers(7));
        p.setProjectStatusValue(ProjectStatusEnum.WAIT_CHECK.getValue());
        p.setProjectStatusLabel(ProjectStatusEnum.WAIT_CHECK.getLable());
        p.setCreateUserType(CreateUserTypeEnum.WECHAT_USER.getValue());
        boolean save = projectService.save(p);
        Assert.isTrue(save, CodeException::new);

//        String image = ProjectCoverImage.randomImageCover();

        // 随机选择封面图
//        attachmentService.save(Attachment.builder()
//                .objId(p.getProjectId())
//                .objType(AttachmentObjTypeEnum.projectIndexCover.getValue())
//                .filePath(image)
//                .build());

        // 详情封面图
//        attachmentService.save(Attachment.builder()
//                .objId(p.getProjectId())
//                .objType(AttachmentObjTypeEnum.projectDetailCover.getValue())
//                .filePath(image)
//                .build());

        return Resp.success(new ProjectCreateResp(p.getProjectId()));
    }

    @Operation(summary = "阿里云ststoken")
    @PostMapping("/aliyun/ststoken/get")
    public Resp<AliyunSts> get() {
        return Resp.success(AliyunStsUtil.get());
    }

}
